package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.utils.RequestPermission;
import cn.wolfcode.utils.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckedPermissionInterceptor implements HandlerInterceptor {
    @Autowired
    private IPermissionService permissionService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //先判断是否为管理员
        Employee employee = UserContext.getEmployee();

        if (employee.isAdmin()){
            return true ;
        }
        //不是管理员
        //判断页面是否需要权限访问
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequestPermission methodAnnotation = handlerMethod.getMethodAnnotation(RequestPermission.class);
        if (methodAnnotation==null){
            return true ;
        }
        //页面需要权限访问
        //判断用户是否有此权限  1>先获取权限表达式
        String expression = methodAnnotation.expression();
        //2>查看用户拥有哪些权限
        List<String> permissions =UserContext.getExpressions();
        if (permissions.contains(expression)){
            return true ;
        }

        //用户不是管理员,也没有访问该页面的权限
        response.sendRedirect("/nopermission");
        return false;
    }
}
